package com.example.order.config;


import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import feign.Logger;
import feign.Retryer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;


@Slf4j
@Configuration
public class ServiceConfig {


    /**
     * 打印完整feign调用日志 2步
     * 1、logging:
     *      level:
     *        com.example.order.feign: debug
     *  2.
     *     @Bean
     *     Logger.Level feignLoggerLevel() {
     *         return Logger.Level.FULL;
     *     }
     * @return
     */
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }


    /**
     * openfeign重试机制
     * 使用默认的重试机制，可以实现Retryer接口实现自己的重试机制
     * @return
     */
//    @Bean
//    Retryer retryer() {
//        return new Retryer.Default();
//    }


    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }


    /**
     * 需求: 在项目启动时监听配置文件的变化，然后进行邮件通知
     * @return
     */
    @Bean
    ApplicationRunner applicationRunner(NacosConfigManager nacosConfigManager) {
        return args -> {
            ConfigService configService = nacosConfigManager.getConfigService();
            configService.addListener("service-order.yml", "DEFAULT_GROUP", new Listener() {
                @Override
                public Executor getExecutor() {
                    return Executors.newFixedThreadPool(2);
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("配置信息发生变化: {}", configInfo);
                }
            });

            log.info("Config listener started.");
        };
    }
}
